package com.kun;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.StandardCharsets;

/**
 * @author fangkun
 * @create 2023-02-06-11:01
 */
@SpringBootApplication
public class springboot2TestApplication {

    private static String CHANNEL = "didispace";

    public static void main(String[] args) {
        SpringApplication.run(springboot2TestApplication.class,args);
    }

    @RestController
    static class RedisController {

        private RedisTemplate<String,String> redisTemplate;

        public RedisController(RedisTemplate<String,String> redisTemplate) {
            this.redisTemplate = redisTemplate;
        }

        @GetMapping("/publish")
        public void publish(@RequestParam String message){
            redisTemplate.convertAndSend(CHANNEL,message);
        }
    }

    @Slf4j
    @Service
    static class MessageSubscriber {
        public MessageSubscriber(RedisTemplate redisTemplate) {
            RedisConnection connection = redisTemplate.getConnectionFactory().getConnection();
            connection.subscribe(new MessageListener() {
                @Override
                public void onMessage(Message message, byte[] bytes) {
                    log.info("收到消息 ： " + message);
                }
            },CHANNEL.getBytes(StandardCharsets.UTF_8));
        }
    }
}

